package com.songcha.module_bookdetail.ui.activity.more_comment

import android.content.Intent
import android.graphics.drawable.Drawable
import android.os.Bundle
import android.view.View
import android.view.View.OnClickListener
import android.view.ViewGroup.MarginLayoutParams
import androidx.core.graphics.drawable.toBitmap
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.bumptech.glide.Glide
import com.bumptech.glide.load.DataSource
import com.bumptech.glide.load.engine.GlideException
import com.bumptech.glide.request.RequestListener
import com.bumptech.glide.request.target.Target
import com.chad.library.adapter.base.viewholder.BaseViewHolder
import com.scwang.smart.refresh.layout.SmartRefreshLayout
import com.songcha.external_blurry.blurry.Blurry
import com.songcha.library_base.mvvm.base.BaseRefreshLoadMoreMvvmActivity
import com.songcha.library_business.bean.book.BookBean
import com.songcha.library_business.handler.BookStatusHandler
import com.songcha.library_business.util.BusinessJumpUtil
import com.songcha.library_common.ui.view.HeaderBarView
import com.songcha.library_common.util.GlideUtil
import com.songcha.library_common.util.StatusBarUtil
import com.songcha.library_common.util.StringUtil
import com.songcha.library_common.util.ToastUtil
import com.songcha.library_common.util.dp2px
import com.songcha.module_bookdetail.R
import com.songcha.module_bookdetail.databinding.BookdetailActivityMoreCommentBinding
import com.songcha.module_bookdetail.event.CommentReportSuccessEvent
import com.songcha.module_bookdetail.ui.activity.catalog.BookCatalogActivity
import com.songcha.module_bookdetail.ui.adapter.BookCommentAdapter
import com.songcha.module_bookdetail.ui.dialog.CommentWriteDialog
import org.greenrobot.eventbus.EventBus
import org.greenrobot.eventbus.Subscribe

class MoreBookCommentActivity:BaseRefreshLoadMoreMvvmActivity<MoreBookCommentViewModel,BookdetailActivityMoreCommentBinding>() ,OnClickListener{
    private var mAdapter: BookCommentAdapter<BookdetailActivityMoreCommentBinding>? = null

    override fun getLayoutId(): Int {
        return R.layout.bookdetail_activity_more_comment
    }



    override fun initView(savedInstanceState: Bundle?) {
        super.initView(savedInstanceState)

        EventBus.getDefault().register(this)

        intent?.let {
            viewModel.bookDetail = it.getParcelableExtra("book_detail")
        }

        if (viewModel.bookDetail == null) {
            ToastUtil.show("无法获取书籍信息")
            finish()
            return
        }

        databinding.bookdetailIvBack.layoutParams =
            databinding.bookdetailIvBack.layoutParams?.apply {
                this as MarginLayoutParams
                topMargin = StatusBarUtil.getStatusBarHeight(this@MoreBookCommentActivity)
            }

        databinding.bookdetailClParent.layoutParams =
            databinding.bookdetailClParent.layoutParams?.apply {
                this as MarginLayoutParams
                topMargin = StatusBarUtil.getStatusBarHeight(this@MoreBookCommentActivity) + HeaderBarView.DEFAULT_HEIGHT
            }

        initData()

        //initRcv()

        initThumbBg()

        databinding.bookdetailIvBack.setOnClickListener(this)
        databinding.bookdetailLlToCatalog.setOnClickListener(this)
        databinding.bookdetailBtnWriteComment.setOnClickListener(this)
        databinding.bookdetailBtnRead.setOnClickListener(this)
        databinding.bookdetailBtnStar.setOnClickListener(this)

        viewModel.bookCommentTotalCount.observe(this){data->
            if(data==0){
                databinding.bookdetailTvCommentCount.text="暂无评论"
            }else{
                databinding.bookdetailTvCommentCount.text="书评·${data}"
            }

        }

        viewModel.getIsBookInShelf()
        viewModel.isInBookShelf.observe(this){isStared->
            if(isStared){
                databinding.bookdetailBtnStar.text="取消收藏"
            }else{
                databinding.bookdetailBtnStar.text="收藏"
            }
        }

    }

    override fun onGetLoadMoreData() {
        viewModel.getBookComment()
    }

    override fun initListData() {
        databinding.bookdetailRcvComment.apply {
            layoutManager = LinearLayoutManager(context)
            mAdapter = BookCommentAdapter(viewModel.rlst.value!!,true)
            adapter = mAdapter
        }
    }

        override fun getRefreshLayout(): SmartRefreshLayout {
            return databinding.bookdetailSrl.apply {
                setEnableRefresh(false)
            }
        }

        override fun getListAdapter(): RecyclerView.Adapter<BaseViewHolder>? {
            if (mAdapter == null) return null
            return mAdapter as RecyclerView.Adapter<BaseViewHolder>?
        }

        override fun onGetData() {
            viewModel.getBookComment()
        }


        private fun initData() {
            GlideUtil.loadNetImage(databinding.bookdetailIvThumb,viewModel.bookDetail!!.cover)
            databinding.bookdetailTvBookname.text = viewModel.bookDetail!!.bookName
            databinding.bookdetailTvAuthor.text = viewModel.bookDetail!!.author
            databinding.bookdetailTvUpdate.text =
                StringUtil.float2PlainString(viewModel.bookDetail!!.words / 10000f) + "万字/" + BookStatusHandler.handle(
                    viewModel.bookDetail!!.status
                )
            databinding.bookdetailTvDesc.text = viewModel.bookDetail!!.description
            databinding.bookdetailSdvScore.setNumber(viewModel.bookDetail!!.averageRating)
            databinding.bookdetailRating.setScore(viewModel.bookDetail!!.averageRating.toInt())
            if(viewModel.bookDetail!!.averageRating>0f){
                databinding.bookdetailRating.visibility=View.VISIBLE
            }else{
                databinding.bookdetailRating.visibility=View.GONE
            }
        }

        private fun initThumbBg() {
            Glide.with(this).load(viewModel.bookDetail!!.cover)
                .listener(object : RequestListener<Drawable> {
                    override fun onLoadFailed(
                        e: GlideException?,
                        model: Any?,
                        target: Target<Drawable>?,
                        isFirstResource: Boolean
                    ): Boolean {
                        return false
                    }

                    override fun onResourceReady(
                        resource: Drawable?,
                        model: Any?,
                        target: Target<Drawable>?,
                        dataSource: DataSource?,
                        isFirstResource: Boolean
                    ): Boolean {
                        //Blurry.with(this@MoreBookCommentActivity).radius(25).sampling(2).onto(databinding.bookdetailFlThumbBg)
                        resource?.let {
                            //val bitmap=BitmapUtil.drawable2Bitmap(resource)
                            // Blurry.with(this@MoreBookCommentActivity).from(bitmap).into(databinding.bookdetailIvThumbBg)
                            //val bitmap = BitmapUtil.drawable2Bitmap(resource)
                            Blurry.with(this@MoreBookCommentActivity).from(it.toBitmap())
                                .into(databinding.bookdetailIvThumbBg)
                        }
                        return true
                    }

                })
                .into(databinding.bookdetailIvThumbBg)
        }


        override fun isImmerseStatusBar(): Boolean {
            return true
        }

    override fun onDestroy() {
        super.onDestroy()
        EventBus.getDefault().unregister(this)
    }

    @Subscribe
    fun onCommentReportSuccess(event: CommentReportSuccessEvent){
        viewModel.getBookComment()
    }

    override fun onClick(v: View?) {
        if(v==null) return
        when(v.id){
            R.id.bookdetail_iv_back->{
                finish()
            }
            R.id.bookdetail_btn_write_comment->{
                val dialog = CommentWriteDialog(v.context, viewModel.bookDetail!!.bookId.toString())
                dialog.show()
            }
            R.id.bookdetail_ll_to_catalog->{
                val intent = Intent(v.context, BookCatalogActivity::class.java)
                //intent.putExtra("book_id", viewModel.bookDetail!!.bookId.toString())
                intent.putExtra("book_detail",viewModel.bookDetail)
                startActivity(intent)
            }
            R.id.bookdetail_btn_star->{
                if(viewModel.isInBookShelf.value!!){
                    viewModel.removeBookFromShelf()
                    ToastUtil.show("已取消收藏")
                }else{
                    viewModel.addBookToShelf()
                    ToastUtil.show("已添加到收藏")
                }
            }
            R.id.bookdetail_btn_read->{
                val bookDetail=viewModel.bookDetail?:return
                val book= BookBean()
                book.id=bookDetail.bookId.toString()
                book.bookName=bookDetail.bookName
                book.thumb=bookDetail.cover
                book.isFromSDCard=false
                book.textCount=bookDetail.words
                book.author=bookDetail.author
                BusinessJumpUtil.toBookReader(book)
            }


        }
    }

}
